<template>
  <!-- 账号管理 表单 -->
  <a-modal
    v-model:open="visible"
    :title="isEdit ? '编辑账号信息' : '账号信息'"
    class="addStation"
    destroyOnClose
    :width="520"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
      :disabled="!isEdit"
    >
      <div class="title">主账号信息</div>
      <a-form-item label="主账号" name="account">
        <a-input
          v-model:value="form.account"
          class="formInput"
          placeholder="（主账号初始密码统一为“NGP@2025”）"
        />
        <a-popconfirm
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleResetPassword"
        >
          <template #title> 是否重置账号密码? </template>
          <a-button
            key="submit"
            type="link"
            :loading="resetLoading"
            size="small"
            >重置密码</a-button
          >
        </a-popconfirm>
      </a-form-item>
      <a-form-item label="主账号状态" name="enable">
        <a-select v-model:value="form.enable" class="formInput">
          <a-select-option :value="1">启用</a-select-option>
          <a-select-option :value="0">禁用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="所属角色" name="roleIds">
        <a-tree-select
          v-model:value="form.roleIds"
          :tree-data="roleList"
          tree-checkable
          class="formInput"
          allow-clear
          :field-names="{
            label: 'name',
            value: 'id',
            children: 'childRoleList',
          }"
          :show-checked-strategy="SHOW_PARENT"
          placeholder="请选择"
          tree-node-filter-prop="label"
          @change="changeRole"
        />
      </a-form-item>

      <a-form-item label="电站权限" name="stationPermiType">
        <a-select v-model:value="form.stationPermiType" class="formInput">
          <a-select-option :value="1">所有</a-select-option>
          <a-select-option :value="2">仅本企业关联电站</a-select-option>
          <a-select-option :value="3">自定义</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="电站名称"
        name="station"
        v-if="form.stationPermiType === 3"
      >
        <a-select
          v-model:value="form.station"
          class="formInput"
          placeholder="请选择"
          mode="multiple"
          show-search
          optionFilterProp="label"
          allow-clear
        >
          <a-select-option
            v-for="item in stationtList"
            :value="item.stationId"
            :key="item.stationId"
            :label="item.stationName"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button
          type="link"
          size="small"
          class="addChildBtn"
          @click="handleChildUser"
          >新增子账号</a-button
        >
      </a-form-item>
      <!-- 子账号数据 -->
      <div v-for="(item, index) in form.childData" :key="item.id">
        <div class="title">
          子账号信息{{ index + 1 }}
          <a-button
            key="submit"
            type="link"
            danger
            size="small"
            @click="deleteChild(item)"
            >删除</a-button
          >
        </div>
        <a-form-item
          label="子账号"
          :name="['childData', index, 'account']"
          :rules="{
            required: true,
            message: '请输入',
            trigger: 'change',
          }"
        >
          <a-input
            v-model:value="item.account"
            class="formInput"
            placeholder="请输入"
          />
          <a-button
            key="submit"
            type="link"
            :loading="resetLoading"
            size="small"
            @click="handleResetChildPassword(item)"
            >重置密码</a-button
          >
        </a-form-item>
        <a-form-item
          label="子账号名称"
          :name="['childData', index, 'username']"
          :rules="{
            required: true,
            message: '请输入',
            trigger: 'blur',
          }"
        >
          <a-input
            v-model:value="item.username"
            class="formInput"
            placeholder="请输入"
          />
        </a-form-item>
        <a-form-item
          label="子账号状态"
          :name="['childData', index, 'enable']"
          :rules="{
            required: true,
            message: '请选择',
            trigger: 'change',
          }"
        >
          <a-select v-model:value="item.enable" class="formInput">
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="所属角色"
          :name="['childData', index, 'roleIds']"
          :rules="{
            required: true,
            message: '请选择',
            trigger: 'change',
          }"
        >
          <a-tree-select
            v-model:value="item.roleIds"
            :tree-data="roleList"
            tree-checkable
            class="formInput"
            allow-clear
            :field-names="{
              label: 'name',
              value: 'id',
              children: 'childRoleList',
            }"
            :show-checked-strategy="SHOW_PARENT"
            placeholder="请选择"
            tree-node-filter-prop="label"
            @change="changeRole"
          />
        </a-form-item>

        <a-form-item
          label="电站权限"
          :name="['childData', index, 'stationPermiType']"
          :rules="{
            required: true,
            message: '请选择',
            trigger: 'change',
          }"
        >
          <a-select v-model:value="item.stationPermiType" class="formInput">
            <a-select-option :value="1">所有</a-select-option>
            <a-select-option :value="2">仅本企业关联电站</a-select-option>
            <a-select-option :value="3">自定义</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="电站名称"
          :name="['childData', index, 'station']"
          :rules="{
            required: true,
            message: '请选择',
            trigger: 'change',
          }"
          v-if="item.stationPermiType === 3"
        >
          <a-select
            v-model:value="item.station"
            class="formInput"
            placeholder="请选择"
            mode="multiple"
            show-search
            optionFilterProp="label"
            allow-clear
          >
            <a-select-option
              v-for="item in stationtList"
              :value="item.stationId"
              :key="item.stationId"
              :label="item.stationName"
            >
              {{ item.stationName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </div>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          v-if="!isEdit"
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleEdit"
          >编辑</a-button
        >
        <a-button
          v-if="isEdit"
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>

  <!-- 子账号 -->
  <AddChildUser
    :addChildUserVisible="addChildUserVisible"
    :rowData="rowData"
    @update:addChildUserVisible="addChildUserVisible = $event"
    @handleSaveChildCB="handleSaveChildCB"
  />

  <!-- 重置子账号密码 -->
  <ResetPassWord
    :resetPassWordVisible="resetPassWordVisible"
    :rowData="childRowData"
    @update:resetPassWordVisible="resetPassWordVisible = $event"
  />
</template>
<script setup>


import AddChildUser from "./addChildUser.vue";
import ResetPassWord from "./resetChildPassWord.vue";
const $api = inject("$api");
const props = defineProps({
  accountManageVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
});
const loading = ref(false);
const resetLoading = ref(false);
const visible = ref(props.accountManageVisible);
const addChildUserVisible = ref(false);
const isEdit = ref(false);
const resetPassWordVisible = ref(false);
const emits = defineEmits(["update:accountManageVisible", "getCompageList"]);
watch(
  () => props.accountManageVisible,
  (val) => {
    visible.value = val;
    if (val) {
      getRoleList();
      getUserListById();
      getCompanyStationtList();
    }
  }
);
const labelCol = { style: { width: "100px" } };
const formRef = ref(null);
const form = ref({
  account: null,
  enable: 1,
  roleIds: undefined,
  stationPermiType: 2,
  station: undefined,
  childData: [],
});
const rules = ref({
  account: [
    {
      required: true,
      message: "请输入主账号",
    },
  ],
  enable: [
    {
      required: true,
      message: "请选择主账号状态",
    },
  ],
  roleIds: [
    {
      required: true,
      message: "请选择所属角色",
    },
  ],
  stationPermiType: [
    {
      required: true,
      message: "请选择电站权限",
    },
  ],
  station: [
    {
      required: true,
      message: "请选择电站",
    },
  ],
  account: [{ required: true, message: "请输入子账号" }],
});
const cancel = () => {
  emits("update:accountManageVisible", false);
  form.value = {
    account: null,
    enable: 1,
    roleIds: undefined,
    stationPermiType: 2,
    station: undefined,
    childData: [],
  };
  isEdit.value = false;
  formRef.value.clearValidate();
};
const roleSelectedOptions = ref([]);
const changeRole = (val) => {
  roleSelectedOptions.value = val;
};
const roleList = ref([]);
const getRoleList = async () => {
  const res = await $api.roleList({
    roleType: 1, // 1 企业角色 2 内部角色组 3 内部子角色
  });
  if (res.code === 0) {
    roleList.value = res.data;
  }
};
const getUserListById = async () => {
  const params = {
    companyId: props.rowData.id,
  };
  const res = await $api.companyUserList(params);
  if (res.code === 0 && res.data) {
    const masterData = res.data.master[0]; // 主账号数据
    form.value = {
      account: masterData?.account || null,
      enable: masterData?.enable || 1,
      roleIds: masterData?.roleIds || undefined,
      stationPermiType: masterData?.stationPermiType || 2,
      station: masterData?.station || undefined,
      childData: res.data.child, // 子账号数据
    };
  }
};
const handleResetPassword = async () => {
  resetLoading.value = true;
  const params = {
    userType: 2, // 1：内部用户 2：企业主账号 3：企业子账号
  };
  const res = await $api.userResetPwd(props.rowData.masterAccountId, params);
  resetLoading.value = false;
  if (res && res.code === 0) {
    message.success("重置成功");
    emits("getCompageList");
  }
};
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      let { childData, ...rest } = form.value;
      childData = childData.map((item) => {
        return {
          id: item.id,
          account: item.account,
          roleIds: item.roleIds,
          enable: item.enable,
          stationPermiType: item.stationPermiType,
          station: item.station,
        };
      });
      const params = [
        ...childData,
        {
          ...rest,
          id: props.rowData.masterAccountId,
          roleIds: roleSelectedOptions.value,
        },
      ];
      loading.value = true;
      const res = await $api.userBatch(params, "put");
      loading.value = false;
      if (res.code === 0) {
        message.success("编辑成功");
        cancel();
        emits("getCompageList");
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const stationtList = ref([]);
const getCompanyStationtList = async () => {
  const res = await $api.companyStationtList();
  if (res.code === 0) {
    stationtList.value = res.data;
  }
};
const handleChildUser = () => {
  addChildUserVisible.value = true;
};
const handleSaveChildCB = () => {
  getUserListById();
};
const handleEdit = () => {
  isEdit.value = true;
};
const childRowData = ref({});
const handleResetChildPassword = (data) => {
  resetPassWordVisible.value = true;
  childRowData.value = data;
};
const deleteChild = async (data) => {
  const res = await $api.userDel(data.id);
  if (res && res.code === 0) {
    message.success("删除成功");
    handleSaveChildCB();
    emits("getCompageList");
  }
};
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 280px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.areaSelectContent {
  display: inline-block;
}
.areaSelectContent {
  display: inline-block;
}
.areaSelect {
  display: inline-block;
  width: 113px;
  margin-right: 5px;
  &:last-child {
    margin-right: 0;
  }
}
.addChildBtn {
  position: relative;
  left: 10px;
}
.formItem {
  width: 200px;
}
.title {
  font-size: 16px;
  width: 100%;
  margin-top: 20px;
}
</style>